package com.mezz.bones.im.gateway.handler.codec;
import com.alibaba.fastjson.JSONObject;
import com.mezz.bones.im.common.message.base.Message;
import com.mezz.bones.im.common.domain.user.ImUserConnectInfo;
import com.mezz.bones.im.gateway.manager.UserConnectInfoManager;
import com.mezz.bones.im.gateway.service.IUserChannelService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author mezz
 * @date 2022-09-23 10:46
 * @description:
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class Decode2ImMessageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

  @Resource
  private IUserChannelService userChannelService;

  @Resource
  private UserConnectInfoManager userConnectInfoManager;

  /**
   * websocket 解析成 业务模型对象
   * @param ctx
   * @param msg
   * @throws Exception
   */
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {

    log.debug("-----------Decode2ImMessageHandler begin-----------");

    // 记录消息内容
    log.debug("Received message: {}", msg.text());
    Message message = JSONObject.parseObject(msg.text(), Message.class);
    userChannelService.validMsgData(message);

    ctx.fireChannelRead(message);
  }

}
